<script setup>
import PageContainer from '@/components/PageContainer.vue'
import { ref } from 'vue'
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus'
import { resetPasswordService } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

// Form state
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})

// Form validation rules
const rules = {
  old_pwd: [
    { required: true, message: '原密码不能为空', trigger: 'blur' },
    { min: 6, max: 15, message: '原密码长度为6-15位', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === pwdForm.value.new_pwd) {
          callback(new Error('原密码和新密码不能相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  new_pwd: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    { min: 6, max: 15, message: '新密码长度为6-15位', trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    { min: 6, max: 15, message: '确认密码长度为6-15位', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.value.new_pwd) {
          callback(new Error('新密码和确认密码必须一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
const formRef = ref(null)
const userStore = useUserStore()
const router = useRouter()
// Submit form function
const submitForm = async () => {
  await formRef.value.validate()
  // 调后端接口修改密码
  await resetPasswordService(pwdForm.value)
  ElMessage.success('密码修改成功')
  // 清除登录信息
  userStore.setToken('')
  userStore.setUserInfo({})
  // 跳转到登录页面
  router.push('/login')
}

// Reset form function
const resetForm = () => {
  formRef.value.resetFields()
}
</script>
<template>
  <page-container title="重置密码">
    <el-form
      :model="pwdForm"
      :rules="rules"
      ref="formRef"
      label-width="100px"
      size="large"
    >
      <el-form-item label="原密码" prop="old_pwd">
        <el-input
          type="password"
          v-model="pwdForm.old_pwd"
          placeholder="请输入原密码"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input
          type="password"
          v-model="pwdForm.new_pwd"
          placeholder="请输入新密码"
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="re_pwd">
        <el-input
          type="password"
          v-model="pwdForm.re_pwd"
          placeholder="请确认新密码"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">修改密码</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </page-container>
</template>

<style lang="scss" scoped>
.el-input {
  width: 40%; // Ensure all inputs take the same width
}
</style>
